package com.pxmeta.party.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.party.entity.PartyDispatch;
import com.pxmeta.party.entity.dto.DispatchDTO;
import com.pxmeta.party.entity.dto.OperateDispatchDTO;
import com.pxmeta.party.mapper.PartyDispatchMapper;
import com.pxmeta.party.service.IPartyDispatchService;
import com.pxmeta.skill.service.IUserSkillService;
import com.pxmeta.user.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class PartyDispatchServiceImpl extends ServiceImpl<PartyDispatchMapper, PartyDispatch> implements IPartyDispatchService {

    @Autowired
    private IUserSkillService userSkillService;

    @Override
    public void dispatch(DispatchDTO dto) {

        PartyDispatch dispatchDetail = this.getDispatchDetail(dto.getPartyId());
        if (null!=dispatchDetail){
            throw new ServiceException("有正在进行中的订单！");
        }
        PartyDispatch partyDispatch = new PartyDispatch();
        partyDispatch.setPartyId(dto.getPartyId());
        partyDispatch.setRemark(dto.getRemark());
        partyDispatch.setSkillName(dto.getSkillName());
        partyDispatch.setSex(dto.getSex());
        partyDispatch.setSkillId(dto.getSkillId());
        partyDispatch.setStatus(Status.PENDING.getValue());
        this.save(partyDispatch);



        List<User> list = userSkillService.sendAccompanyUsers(dto.getPartyId(), dto.getSkillId(), dto.getSex(),dto.getRemark(),partyDispatch.getId());

    }

    @Override
    public PartyDispatch getDispatchDetail(String partyId) {
        LambdaQueryWrapper<PartyDispatch> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PartyDispatch::getPartyId, partyId)
                .eq(PartyDispatch::getStatus, Status.PENDING.getValue());

        return this.getOne(wrapper,false);
    }

    @Override
    public void completeDispatch(OperateDispatchDTO dto) {
        PartyDispatch dispatchDetail = getDispatchDetail(dto.getPartyId());
        if (null == dispatchDetail){
            throw new ServiceException("没有正在进行中的订单！");
        }
        dispatchDetail.setStatus(Status.SUCCESS.getValue());
        this.updateById(dispatchDetail);
    }

    @Override
    public void cancelDispatch(OperateDispatchDTO dto) {
        PartyDispatch dispatchDetail = getDispatchDetail(dto.getPartyId());
        if (null == dispatchDetail){
            throw new ServiceException("没有正在进行中的订单！");
        }
        dispatchDetail.setStatus(Status.FAIL.getValue());
        this.updateById(dispatchDetail);
    }
}
